<template>
    <div class="app-container">
      <div class="filter-container">
        <div class="lineBox">
          <el-form :inline="true" :model="listQuery" class="demo-form-inline">
          
  
            <el-form-item label="状态">
              <el-select
                v-model="listQuery.status"
                placeholder="请选择状态"
                style="width: 140px"
                size="mini"
                clearable
                @change="handleFilter"
              >
                <el-option label="未处理" :value="0" />
                <el-option label="已处理" :value="1" />
                <el-option label="处理异常" :value="2" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button size="mini" type="primary" icon="el-icon-search" @click="handleFilter">
                搜索
              </el-button>
              <el-button size="mini" icon="el-icon-refresh" @click="handleReset">
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
  
      <div class="queue-table" style="min-height: 600px; margin-top: 20px;">
        <div style="margin-bottom: 10px;">
          <!-- <el-button 
            size="mini" 
            type="danger" 
            :disabled="selectedIds.length === 0" 
            @click="handleBatchDelete"
          >
            批量删除
          </el-button> -->
          <el-button 
            size="mini" 
            type="primary" 
            icon="el-icon-refresh" 
            @click="handleRefresh"
          >
            刷新数据
          </el-button>
        </div>
  
        <el-table
          :key="tableKey"
          v-loading="listLoading"
          :data="list"
          fit
          size="mini"
          highlight-current-row
          style="width: 100%;"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="ID" prop="id" align="center" width="80" />
          <el-table-column label="题名" prop="tm" align="center" min-width="180" show-overflow-tooltip />
          <el-table-column label="全宗号" prop="qzh" align="center" min-width="180" show-overflow-tooltip />
          <el-table-column label="文件夹" prop="folder" align="center" min-width="150" show-overflow-tooltip />
       
          <el-table-column label="状态" prop="z_status" align="center" width="100">
            <template slot-scope="{row}">
              <!-- {{row.is_synpdf}} -->
              <el-tag  v-if="row.auto_status == 1" type="success" size="small">
               已处理
              </el-tag>
              <el-tag  v-if="row.auto_status == 0 || row.auto_status == 2" type="info" size="small">
                  未处理
              </el-tag>
              <!-- <el-tag  v-if="row.auto_status == 2" type="danger" size="small">
                  处理异常
              </el-tag> -->
          
            </template>
          </el-table-column>
          <el-table-column label="文件路径" prop="file_path" align="center" min-width="200" show-overflow-tooltip />
          <el-table-column label="创建时间" align="center" min-width="150">
            <template slot-scope="{row}">
              <span>{{ row.create_time | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="更新时间" align="center" min-width="150">
            <template slot-scope="{row}">
              <span>{{ row.update_time | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" min-width="250" class-name="small-padding fixed-width">
           
            <template slot-scope="{row,$index}">
              <el-button 
               
                size="mini" 
                type="warning" 
                icon="el-icon-refresh-right" 
                @click="handleManualRerun(row)"
              >
                重新执行
              </el-button>
              
            </template>
          </el-table-column>
        </el-table>
        <pagination
          size="mini"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          :page.sync="listQuery.page"
          :limit.sync="listQuery.limit"
          layout="total, sizes, prev, pager, next, jumper"
          @pagination="getList"
        />
      </div>
  
      <!-- 文档预览对话框 -->
      <el-dialog title="文档预览" :visible.sync="previewDialogVisible" width="70%" :append-to-body="true">
        <div v-if="currentDocument" class="preview-container">
          <iframe v-if="pdfUrl" :src="pdfUrl" frameborder="0" width="100%" height="500"></iframe>
          <div v-else class="empty-preview">
            暂无预览，不支持该文件类型或文件不存在
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="previewDialogVisible = false">关闭</el-button>
        </span>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { autoqueApi } from '@/api/autoque'
  import { artqueueApi } from '@/api/artqueue'
  import { reexecute } from '@/api/artqueue'
  import Pagination from '@/components/Pagination'
  import { parseTime } from '@/utils'
  
  export default {
    name: 'ArtQueue',
    components: { Pagination },
    filters: {
      parseTime
    },
    data() {
      return {
        tableKey: 0,
        list: [],
        total: 0,
        listLoading: false,
        selectedIds: [],
        previewDialogVisible: false,
        currentDocument: null,
        pdfUrl: '',
        listQuery: {
          page: 1,
          limit: 10,
          status: "",
          task_id: "",
          is_delete: '0' // 默认查询未删除的记录
        }
      }
    },
    created() {
      // 检查URL是否包含que参数
      const queryParams = new URLSearchParams(window.location.search)
      if (queryParams.has('taskid')) {
        this.listQuery.task_id = queryParams.get('taskid')

      }
      this.getList()
    },
    mounted() {
      // 3秒后检查是否有数据，如果没有就显示提示
      setTimeout(() => {
        if (this.list.length === 0 && !this.listLoading) {
          this.$message.warning('暂无数据，或者后端API尚未完全配置')
        }
      }, 3000)
    },
    methods: {
      async getList() {
        this.listLoading = true
        try {
          // 添加调试信息
          console.log('发送请求参数:', this.listQuery)
          
          let response
          try {
            response = await autoqueApi('getAutoqueList', this.listQuery)
          } catch (apiError) {
            console.error('API调用失败:', apiError)
            // 使用模拟数据
          }
          
          console.log('返回数据:', response)
          
          if (response.code == 200) {
            // 处理后端返回的实际数据结构
            if (response.data && response.data.items) {
              // 新的数据结构 {total: x, items: [...], page: x, limit: x}
              this.list = response.data.items
              this.total = response.data.total || 0
              
              // 如果后端返回了页码和分页大小，同步到前端
              if (response.data.page) {
                this.listQuery.page = response.data.page
              }
              if (response.data.limit) {
                this.listQuery.limit = response.data.limit
              }
            } else if (response.data && response.data.resultList) {
              // 旧的数据结构处理方式
              this.list = response.data.resultList
              this.total = response.data.totalCount || response.totalCount || 0
            } else if (Array.isArray(response.data)) {
              // 直接返回数组的情况
              this.list = response.data
              this.total = response.totalCount || response.data.length || 0
            } else {
              // 数据结构不符合预期
              console.warn('后端返回的数据结构不符合预期:', response.data)
              this.list = []
              this.total = 0
              
              // 如果没有返回有效数据，可以考虑使用测试数据
              this.useTestData()
            }
            
            setTimeout(() => {
              this.listLoading = false
            }, 300)
          } else {
            this.$message.error(response.message || '获取列表失败')
            this.listLoading = false
            // API调用返回错误，使用测试数据
            this.useTestData()
          }
        } catch (error) {
          console.error('获取列表失败:', error)
          this.$message.error('获取列表失败，显示测试数据')
          this.listLoading = false
          // API调用异常，使用测试数据
          this.useTestData()
        }
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      handleReset() {
        // 保留que参数
        const que = this.listQuery.que
        this.listQuery = {
          page: 1,
          limit: 10,
          folder: que, // 保持和que相同
          article_type: undefined,
          status: undefined,
          que: que, // 保留que参数
          is_delete: '0' // 保持未删除的查询条件
        }
        this.getList()
      },
      handleRefresh() {
        // 直接刷新数据，不修改查询条件
        this.getList()
      },
      handleSelectionChange(val) {
        this.selectedIds = val.map(item => item.id)
      },
      
      // 查看文档预览
      async handleViewDocument(row) {
        this.currentDocument = row
        this.previewDialogVisible = true
        
        if (row.file_path) {
          try {
            const response = await artqueueApi('getDocumentPreviewUrl', { id: row.id })
            if (response.code == 200 && response.data && response.data.url) {
              this.pdfUrl = response.data.url
            } else {
              // 如果后端没有返回预览URL，尝试使用文件路径构建一个URL
              // 这只是示例，需要根据实际情况调整
              this.pdfUrl = `/api/admin/ArtQueue/preview?path=${encodeURIComponent(row.file_path)}`
            }
          } catch (error) {
            console.error('获取预览URL失败:', error)
            this.$message.error('获取预览URL失败')
            this.pdfUrl = ''
          }
        } else {
          this.pdfUrl = ''
          this.$message.warning('文件路径不存在，无法预览')
        }
      },
      
      // 处理文档
      async handleProcessDocument(row) {
        try {
          this.$confirm('确定要处理该文档吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            const data = { id: row.id }
            const response = await artqueueApi('processDocument', data)
            if (response.code == 200) {
              this.$notify({
                title: '成功',
                message: response.message || '文档处理已启动',
                type: 'success',
                duration: 2000
              })
              // 更新该行数据的状态
              row.status = 1
            } else {
              this.$notify({
                title: '失败',
                message: response.message || '文档处理启动失败',
                type: 'error',
                duration: 2000
              })
            }
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消处理'
            })
          })
        } catch (error) {
          console.error('文档处理失败:', error)
          this.$message.error('文档处理失败')
        }
      },
      
      async handleBatchDelete() {
        if (this.selectedIds.length === 0) {
          this.$message.warning('请选择要删除的记录')
          return
        }
  
        this.$confirm('此操作将永久删除选中的记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          try {
            const data = { ids: this.selectedIds } // 改为直接传递数组格式，而不是逗号连接的字符串
            const response = await artqueueApi('batchDeleteArtQueueList', data)
            if (response.code == 200) {
              this.$notify({
                title: '成功',
                message: response.message || '批量删除成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            } else {
              this.$notify({
                title: '失败',
                message: response.message || '批量删除失败',
                type: 'error',
                duration: 2000
              })
            }
          } catch (error) {
            console.error('批量删除失败:', error)
            this.$message.error('批量删除失败')
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      
      async handleDelete(row, index) {
        this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          try {
            const data = { ids: [row.id] } 
            const response = await artqueueApi('batchDeleteArtQueueList', data)
            if (response.code == 200) {
              this.$notify({
                title: '成功',
                message: response.message || '删除成功',
                type: 'success',
                duration: 2000
              })
              this.list.splice(index, 1)
              // 如果是最后一条记录被删除，且不是第一页，则跳转到上一页
              if (this.list.length === 0 && this.listQuery.page > 1) {
                this.listQuery.page -= 1;
                this.getList();
              }
            } else {
              this.$notify({
                title: '失败',
                message: response.message || '删除失败',
                type: 'error',
                duration: 2000
              })
            }
          } catch (error) {
            console.error('删除失败:', error)
            this.$message.error('删除失败')
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      
      useTestData() {
        if (this.list.length === 0) {
          this.list = [
            {
              id: 1,
              title: '测试文档1',
              folder: this.listQuery.que || 'YWS.WS1955001',
              article_type: '文字',
              status: 0,
              create_time: new Date().toISOString(),
              update_time: new Date().toISOString(),
              file_path: 'directory/1745053605_7667/NJ03南京军区政治部/文字图表/YWS.WS1955001/doc1.pdf'
            },
            {
              id: 2,
              title: '测试文档2',
              folder: this.listQuery.que || 'YWS.WS1955001',
              article_type: '图表',
              status: 1,
              create_time: new Date().toISOString(),
              update_time: new Date().toISOString(),
              file_path: 'directory/1745053605_7667/NJ03南京军区政治部/文字图表/YWS.WS1955001/doc2.pdf'
            },
            {
              id: 3,
              title: '测试文档3',
              folder: this.listQuery.que || 'YWS.WS1955001',
              article_type: '文字',
              status: 0,
              create_time: new Date().toISOString(),
              update_time: new Date().toISOString(),
              file_path: 'directory/1745053605_7667/NJ03南京军区政治部/文字图表/YWS.WS1955001/doc3.pdf'
            }
          ]
          this.total = this.list.length
          
          this.$message.warning('API未配置或返回错误，显示测试数据')
        }
      },

      // 手动重新处理异常记录
      async handleManualRerun(row) {
        try {
          this.$confirm('确定要手动重新处理该异常记录吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            const loading = this.$loading({
              lock: true,
              text: '处理中...',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            })
            
            try {
              const data = { id: row.id }
              const response = await reexecute('manualRerun', data)
              
              loading.close()
              
              if (response.code == 200) {
                this.$notify({
                  title: '成功',
                  message: response.message || '已成功启动手动处理',
                  type: 'success',
                  duration: 2000
                })
                
                // 更新状态为处理中
                row.auto_status = 0
                
                // 刷新列表
                setTimeout(() => {
                  this.getList()
                }, 1000)
              } else {
                this.$notify({
                  title: '失败',
                  message: response.message || '手动处理启动失败',
                  type: 'error',
                  duration: 2000
                })
              }
            } catch (error) {
              loading.close()
              console.error('手动处理失败:', error)
              this.$message.error('手动处理失败: ' + (error.message || '未知错误'))
            }
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消操作'
            })
          })
        } catch (error) {
          console.error('操作异常:', error)
          this.$message.error('操作异常: ' + (error.message || '未知错误'))
        }
      }
    }
  }
  </script>
  
  <style lang="scss" scoped>
  .queue-table {
    background-color: #fff;
    padding: 15px;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  }
  
  .preview-container {
    max-height: 500px;
    overflow-y: auto;
    background-color: #f5f7fa;
    padding: 10px;
    border-radius: 4px;
  }
  
  .empty-preview {
    text-align: center;
    color: #909399;
    padding: 20px 0;
  }
  </style>
  